<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="爬虫名称" prop="crawlName">
              <el-input v-model="queryParams.crawlName" placeholder="请输入爬虫名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="爬虫类型" prop="crawlType">
              <el-select v-model="queryParams.crawlType" placeholder="请选择爬虫类型" clearable>
                <el-option v-for="dict in crawl_source_config_crawl_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="是否启用" prop="crawlEnabled">
              <el-select v-model="queryParams.crawlEnabled" placeholder="请选择是否启用" clearable>
                <el-option v-for="dict in crawl_source_config_crawl_enabled" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['crawl:crawlSourceConfig:add']"> 新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['crawl:crawlSourceConfig:edit']"
              >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['crawl:crawlSourceConfig:remove']"
              >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['crawl:crawlSourceConfig:export']">导出 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="crawlSourceConfigList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="爬虫名称" align="center" prop="crawlName" />
        <el-table-column label="爬虫地址" align="center" prop="crawlUrl" />
        <el-table-column label="爬虫类型" align="center" prop="crawlType">
          <template #default="scope">
            <dict-tag :options="crawl_source_config_crawl_type" :value="scope.row.crawlType" />
          </template>
        </el-table-column>
        <el-table-column label="编码" align="center" prop="charset" />
        <el-table-column label="是否启用" align="center" prop="crawlEnabled">
          <template #default="scope">
            <dict-tag :options="crawl_source_config_crawl_enabled" :value="scope.row.crawlEnabled" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="crawlRemark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleOpen(scope.row)" v-hasPermi="['crawl:crawlSourceConfig:edit']">开启</el-button>
            <el-button link type="primary" icon="Delete" @click="handleClose(scope.row)" v-hasPermi="['crawl:CrawlSourceConfig:remove']"
              >关闭</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
  </div>
</template>

<script setup name="CrawlSourceConfig" lang="ts">
import {
  listCrawlSourceConfig,
  getCrawlSourceConfig,
  delCrawlSourceConfig,
  addCrawlSourceConfig,
  updateCrawlSourceConfig,
  openCrawl,
  closeCrawl
} from '@/api/crawl/config';

import { CrawlSourceConfigVO, CrawlSourceConfigQuery, CrawlSourceConfigForm } from '@/api/crawl/config/types';
import router from '@/router';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { crawl_source_config_crawl_type, crawl_source_config_crawl_enabled } = toRefs<any>(
  proxy?.useDict('crawl_source_config_crawl_type', 'crawl_source_config_crawl_enabled')
);

const crawlSourceConfigList = ref<CrawlSourceConfigVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const crawlSourceConfigFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: CrawlSourceConfigForm = {
  crawlId: undefined,
  crawlName: undefined,
  crawlUrl: undefined,
  crawlType: undefined,
  charset: undefined,
  crawlEnabled: undefined,
  crawlRemark: undefined
};
const data = reactive<PageData<CrawlSourceConfigForm, CrawlSourceConfigQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    crawlName: undefined,
    crawlType: undefined,
    crawlEnabled: undefined,
    params: {}
  },
  rules: {}
});

const { queryParams, form, rules } = toRefs(data);

/** 查询爬虫管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCrawlSourceConfig(queryParams.value);
  crawlSourceConfigList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  crawlSourceConfigFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: CrawlSourceConfigVO[]) => {
  ids.value = selection.map((item) => item.crawlId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  router.push({ path: '/crawl/config/add' });
};

/** 修改按钮操作 */
const handleUpdate = async (row?: CrawlSourceConfigVO) => {
  reset();
  const _crawlId = row?.crawlId || ids.value[0];
  const res = await getCrawlSourceConfig(_crawlId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改爬虫管理';
};
/** 开启爬虫 */
const handleOpen = async (row?: CrawlSourceConfigVO) => {
  const _crawlId = row?.crawlId;
  await openCrawl(_crawlId);
  proxy?.$modal.msgSuccess('开启成功');
};
/** 关闭爬虫 */
const handleClose = async (row?: CrawlSourceConfigVO) => {
  const _crawlId = row?.crawlId;
  await closeCrawl(_crawlId);
  proxy?.$modal.msgSuccess('关闭成功');
};

/** 提交按钮 */
const submitForm = () => {
  crawlSourceConfigFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.crawlId) {
        await updateCrawlSourceConfig(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addCrawlSourceConfig(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: CrawlSourceConfigVO) => {
  const _crawlIds = row?.crawlId || ids.value;
  await proxy?.$modal.confirm('是否确认删除爬虫管理编号为"' + _crawlIds + '"的数据项？').finally(() => (loading.value = false));
  await delCrawlSourceConfig(_crawlIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'crawl/CrawlSourceConfig/export',
    {
      ...queryParams.value
    },
    `CrawlSourceConfig_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
